/*------------------------------------------------------------
 * tcp_recv - Receive a string from a host machine using TCP
 *------------------------------------------------------------*/
#ifndef NIM_HEADER
#define NIM_HEADER
#include "nim.h";
#endif

#ifndef STRING_H
#define STRING_H
#include <string.h>
#endif

#ifndef IOSTREAM
#define IOSTREAM
#include <iostream>
#endif

using namespace std;

int tcp_recv(SOCKET s, char *buf, int maxsize, char *host, char *port)
{	// Parameter List:
	// [IN] s      : SOCKET handle
	// [OUT] buf   : NULL-terminated string that will contain the data received.
	// [IN] maxsize: Integer containing the maximum number of bytes that buf can hold
	// [OUT] host  : NULL-terminated string containing IP Address of machine that sent the data
	// [OUT] port  : NULL-terminated string containing port number on remote host that sent the data
	// Return Value: Number of bytes actually received.

	// NOTES: 1. This function requires winsock2.h header file and ws2_32.lib library file.
	//        2. This function will block until data is received from some other machine.

	sockaddr_in sin;						/* an Intenet endpoint address */
	int         sin_size = sizeof(sin);		/* Needed for sixth parameter in recvfrom function call */
	int         len;						/* Holds return value for recvfrom function call */

	memset(&sin,0,sizeof(sin));				/* zero the sockaddr_in struct */

	/* Wait for and read incoming data from ANY remote host/port */
	len = recvfrom(s, buf, maxsize, 0, (LPSOCKADDR) &sin, &sin_size);
	if (len <= 0 || len > maxsize)
	{	cout << endl << "Problem with recvfrom() function call within tcp_recv().  Return value = " << len << endl;
	}
	else 
	{	// Find the sender's IP address and port #
		strcpy(host,inet_ntoa(sin.sin_addr));
		_itoa(ntohs(sin.sin_port),port,10);
		if (buf[len-1] != '\0')
			if (len < maxsize)
				buf[len] = '\0';
			else
				buf[maxsize-1] = '\0';
	}
	return len;
}